package com.cn.wolf.netty;

import com.cn.wolf.common.Constants;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author huangy
 * @description netty服务端
 * @since 2022/9/29 9:17
 **/
public class NettyServer {

    public static void main(String[] args) throws Exception {
        //创建bossGroup管理连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //创建workGroup处理业务
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("服务器准备好了....");
            //绑定一个端口并且同步，生成一个channelFuture对象
            //启动服务器，并绑定端口
            ChannelFuture future = bootstrap.bind(Constants.PORT).sync();
            //对关闭通道进行监听
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

}
